package com.hcl.orm.core.dialect.handler;

import cn.hutool.core.collection.ListUtil;
import com.hcl.orm.core.annotation.DBType;
import com.hcl.orm.core.dialect.SqlDefinition;
import com.hcl.orm.core.dialect.SqlMetadata;
import com.hcl.orm.core.executor.DataSourceTypeLookup;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author hucl
 * @projectName hcl-orm
 * @description: 包含指定平台脚本处理器
 * @date 2021/8/17 17:46
 */
@Component
@Scope("prototype")
public class TargetScriptHandler extends AbstractDialectHandler {
    private DBType dbType;
    @Resource
    private DataSourceTypeLookup sourceTypeLookup;

    public TargetScriptHandler() {
        super("目标脚本处理器");
    }

    public void setDbType(DBType dbType) {
        this.dbType = dbType;
    }

    @Override
    protected boolean needHandled(SqlDefinition sqlDefinition) {
        return true;
    }

    @Override
    protected void doHandle(SqlDefinition sqlDefinition) {
        final List<SqlMetadata> nativeSqlMetadata = sqlDefinition.getNativeSqlMetadatas();
        SqlMetadata metadata = null;
        if (nativeSqlMetadata != null) {
            metadata = nativeSqlMetadata.stream().filter(m ->
                    m.getTargetType().equals(this.dbType)
            ).findFirst().orElse(null);
        }
        if (metadata != null) {
            sqlDefinition.setSelectedSqlMetadata(metadata);
        } else {
            sqlDefinition.setSelectedSqlMetadata(sqlDefinition.getStdSqlMetadata());
        }
    }

    @Override
    protected List<DBType> getTargetDB() {
        return ListUtil.toList(DBType.ALL);
    }
}
